﻿using System;
using System.Collections;
using System.Drawing;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FSViet.Survey.Helpers;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;

namespace FSViet.Survey.Administration.Question
{
	public partial class List : ListPageBase
	{
		SqlConnection _conn=null;
		DataHelper _dataH = new DataHelper();
		bool IsAnswerGroup
		{
			get
			{
				bool result = false;
				if (Request.QueryString["IsAnswerGroup"] != null)
				{
					result = Convert.ToBoolean(Request.QueryString["IsAnswerGroup"]);
				}
				else
					if (Session["IsAnswerGroup"] != null)
						result = (bool)Session["IsAnswerGroup"];

				Session["IsAnswerGroup"] = result;

				return result;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			CheckCampaign();

			if (!IsPostBack)
			{
				//ListItem.Columns[0].Visible = !IsAnswerGroup;
				if (CampaignId != Guid.Empty)
				{
					LoadData(KeywordInput.Text.Trim());
				}
			}
		}

		void LoadData(string keyword)
		{
			int page = PageIndex;
			page = page - 1;
			if (page < 0) page = 0;
			try
			{
				_conn = _dataH.CreateConnection();
				_conn.Open();
				try
				{
					int totalRecord = 0;

					keyword = keyword.Trim();
					if (keyword.Length>0)
						keyword = " AND Name LIKE N'%" + keyword.Replace("'", "''") + "%'";

					var data = _dataH.Load(_conn,
						"SELECT COUNT(*) FROM Questions WHERE CampaignId=@CampaignId AND IsAnswerGroup=@IsAnswerGroup"+keyword,
						"SELECT * FROM Questions WHERE CampaignId=@CampaignId AND IsAnswerGroup=@IsAnswerGroup "+keyword+"ORDER BY Created",
						page * GlobalApplication.ItemPerPage,
						GlobalApplication.ItemPerPage,
						out totalRecord,
						_dataH.CreateParam("CampaignId", System.Data.SqlDbType.Char, GlobalApplication.GetGuidS(CampaignId)),
						_dataH.CreateParam("IsAnswerGroup", System.Data.SqlDbType.Bit, IsAnswerGroup));

					ShowPage(PageList, totalRecord, GlobalApplication.GetGuidS(CampaignId));

					ListItem.DataSource = data;
					ListItem.DataBind();
				}
				finally
				{
					_conn.Close();
				}
			}
			catch (Exception ex)
			{
				msg.Text = ex.Message;
#if DEBUG
				msg.Text = ex.ToString();
#endif
			}
		}

		//void ShowPage(int totalRecord, string siteId)
		//{
		//  if (totalRecord > GlobalApplication.ItemPerPage)
		//  { }
		//  else
		//  {
		//    PageList.Visible = false;
		//    return;
		//  }

		//  int totalPage = totalRecord / GlobalApplication.ItemPerPage + 1;
		//  var ul = new HtmlGenericControl("ol");
		//  ul.Attributes.Add("class", "pagination");
		//  for (int i = 1; i <= totalPage; i++)
		//  {
		//    var li = new HtmlGenericControl("li");
		//    if (i == PageIndex)
		//    {
		//      li.Attributes.Add("class", "selected");
		//      li.Controls.Add(new HyperLink() { Text = i.ToString(), NavigateUrl = "" });
		//    }
		//    else
		//      li.Controls.Add(new HyperLink() { Text = i.ToString(), NavigateUrl = "?p=" + i.ToString() + "&IsAnswerGroup=" + IsAnswerGroup.ToString() });
		//    ul.Controls.Add(li);
		//  }
		//  PageList.Controls.Add(ul);
		//}

		string BuildPramToDetails()
		{
			string result = string.Empty;

			return result;
		}

		#region helper get color group
		
		Hashtable _groupColor=new Hashtable();
		System.Random _randomGen = new Random(1);

		KnownColor GetRandomColor()
		{
			KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
			return names[_randomGen.Next(names.Length)];
		}

		void SetForeColor(string groupId,HyperLink link)
		{
			if (_groupColor.ContainsKey(groupId))
			{
				link.ForeColor = (Color)_groupColor[groupId];
			}
			else
			{
				var color=Color.FromKnownColor(GetRandomColor());
				_groupColor.Add(groupId, color);
				link.ForeColor = color;
			}
			
		}

		#endregion

		protected void ListItem_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				var drv = (DataRowView)e.Row.DataItem;
				var hpl = e.Row.FindControl("ShowGroupInfo") as HyperLink;
				if (hpl != null)
				{
					hpl.Visible = (drv["GroupId"].ToString() != GlobalApplication.GetGuidS(Guid.Empty));
				}
				
				#region show group info
				
				hpl = e.Row.FindControl("GroupLink") as HyperLink;
				ImageButton imgBtn = e.Row.FindControl("RemoveGroupButton") as ImageButton;
				if (hpl == null 
					|| DBNull.Value == drv["GroupId"] 
					|| drv["GroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
				{
					hpl.Visible = false;
					imgBtn.Visible = false;
				}
				else
				{
					SetForeColor(drv["GroupId"].ToString(), hpl);
					hpl.Visible = true;
					imgBtn.Visible = true;
					imgBtn.CommandName = "RemoveGroup";
					imgBtn.CommandArgument = drv["Id"].ToString();
					try
					{
						var data = _dataH.Load(_conn, "SELECT * FROM Groups WHERE Id=@Id", 0, 1,
							_dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GetGuidS(new Guid(drv["GroupId"].ToString()))));
						if (data.Rows.Count > 0)
						{
							hpl.Text = "<b>Group</b>: " + data.Rows[0]["Name"].ToString();
							hpl.NavigateUrl = "../Group/Details.aspx?Id=" + data.Rows[0]["Id"].ToString();
						}
						else
							hpl.Text = "<b>Group</b>: Unknown";
					}
					catch (Exception ex)
					{
						hpl.Text = ex.Message;
						hpl.ToolTip = ex.ToString();
					}
				}

				#endregion

				#region show answer group info

				hpl = e.Row.FindControl("AnswerGroupLink") as HyperLink;
				if (hpl == null
					|| DBNull.Value == drv["AnswerGroupId"]
					|| drv["AnswerGroupId"].ToString() == GlobalApplication.GetGuidS(Guid.Empty))
				{ }
				else
				{
					hpl.Visible = true;
					try
					{
						var data = _dataH.Load(_conn, "SELECT * FROM Questions WHERE Id=@Id", 0, 1,
							_dataH.CreateParam("Id", SqlDbType.Char, GlobalApplication.GetGuidS(new Guid(drv["AnswerGroupId"].ToString()))));
						if (data.Rows.Count > 0)
						{
							hpl.Text = "<b>Answer group</b>: " + data.Rows[0]["Name"].ToString();
							hpl.NavigateUrl = "Details.aspx?Id=" + data.Rows[0]["Id"].ToString();
						}
						else
							hpl.Text = "<b>Answer group</b>: Unknown";
					}
					catch (Exception ex)
					{
						hpl.Text = ex.Message;
						hpl.ToolTip = ex.ToString();
					}
				}

				#endregion
			}
		}

		protected void ListItem_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (e.CommandName == "RemoveGroup")
			{
				try
				{
					_dataH.Execute("UPDATE Questions SET GroupId='" + GlobalApplication.GetGuidS(Guid.Empty) + "' WHERE Id=@Id",
								_dataH.CreateParam("Id", SqlDbType.Char, e.CommandArgument));
					msg.Text = "Remove group of question: " + e.CommandArgument + " success.";

					LoadData(KeywordInput.Text.Trim());
				}
				catch (Exception ex)
				{
					msg.Text = ex.Message;
#if DEBUG
					msg.Text = ex.ToString();
#endif
				}
			}
		}

		protected void SearchButton_Click(object sender, EventArgs e)
		{
			LoadData(KeywordInput.Text.Trim());
		}

		protected void ReloadButton_Click(object sender, EventArgs e)
		{
			LoadData(KeywordInput.Text.Trim());
		}
	}
}